import router from "."
import { MenuState } from "@/store/modules/auth"
import { prevMenus, postMenus } from "./static-menu"
import { isEmpty, isObject } from "@/utils"
import { RouteRecordRaw } from "vue-router"

const LayoutMap: Recordable = {
    Layout: () => import("@/layout/Index.vue"),
    EmptyLayout: () => import("@/layout/Empty.vue")
}

/**
 * 动态添加路由
 */
export const registerDynamisRouter = (menus: MenuState[], permissions: string[]) => {
    // 加载静态路由
    loadStaticMenus(menus, permissions)
    const routes = generateRoutes(menus)
    routes.forEach(v => router.addRoute(v))
    return routes
}

/**
 * 加载静态菜单
 */
function loadStaticMenus(menus: MenuState[], permissions: string[]) {
    if (!isEmpty(permissions)) {
        const staticPrevMenus = filterMenus(prevMenus, permissions)
        if (!isEmpty(staticPrevMenus)) {
            menus.unshift(...staticPrevMenus)
        }
        const staticPostMenus = filterMenus(postMenus, permissions)
        if (!isEmpty(staticPostMenus)) {
            menus.push(...staticPostMenus)
        }
    }
}

/**
 * 对菜单进行权限过滤
 */
function filterMenus(menus: MenuState[], permissions: string[]) {
    return menus.filter(v => !v.meta || !v.meta.permission || permissions.includes(v.meta.permission))
}

/**
 * 根据后台菜单，组装路由
 */
function generateRoutes(menus: MenuState[], parent?: MenuState): RouteRecordRaw[] {
    return menus.map(menu => {
        const path = determineRoutePath(menu, parent)
        menu.path = path
        const route: Recordable = {
            path,
            // 路由名称，建议唯一
            name: menu.perm ?? "",
            meta: {
                ...menu.meta,
                // 页面标题
                title: menu.name,
                // 菜单图标
                icon: menu.icon ?? null,
                // 是否显示为菜单
                show: menu.visible === true,
                // 登录校验
                needLogin: true
            }
        }
        if (menu.component) {
            if (menu.component.startsWith("/")) {
                route.component = () =>
                    import(/* @vite-ignore */ `/src${menu.component}`).then(component => ({ ...component.default, name: menu.perm }))
            } else {
                route.component = LayoutMap[menu.component]
            }
        }
        if (!isEmpty(menu.children)) {
            route.children = generateRoutes(menu.children ?? [], menu)
            if (isEmpty(route.redirect) && !isEmpty(route.children)) {
                const firstChild = route.children.find((v: any) => v.meta.show)
                if (isObject(firstChild)) {
                    route.redirect = firstChild.path
                }
            }
        }
        return route as RouteRecordRaw
    })
}

/**
 * 确定当前菜单的访问路径
 */
function determineRoutePath(menu: MenuState, parent?: MenuState) {
    if (menu.path.startsWith("/")) {
        return menu.path
    } else {
        return `${(parent && parent.path) ?? ""}/${menu.path}`
    }
}
